package com.example.dict.data;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import com.example.dict.utils.util.Record;


/**
 *
 * 单词存储功能包括新增，删除，只对文件进行操作
 * @author wey
 * */
public class DictionaryStorage {

    /**
     * 存储单词
     * @param record 单词记录
     * */
    public void storage(Record record) throws IOException {

        if (null == record || null == record.word || null == record.translation) {
            return;
        }

        String word = record.word;
        word = word.toLowerCase();
        String src = "dictionary_storage/" + word.charAt(0) + ".txt";

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(src, true))) {

            writer.write(record.word + "\t" + record.translation);
            writer.newLine();

        } catch (IOException e) {
            System.out.println("Error writing to file: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 删除单词纪律
     * @param wordToDelete 待删除单词记录
     * */
    public void deleteRecord(String wordToDelete) throws IOException {
        if (wordToDelete == null || wordToDelete.isEmpty()) {
            return;
        }

        wordToDelete = wordToDelete.toLowerCase();  // 将单词转换为小写，进行大小写不敏感的比较
        String src = "dictionary_storage/" + wordToDelete.charAt(0) + ".txt";  // 假设按首字母存储文件

        // 读取文件内容
        List<Record> records = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(src))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(" ", 2);  // 分割单词和翻译，最大分割成两部分
                if (parts.length == 2) {
                    if (parts[1].equals("translation")) {continue;}
                    if (parts[0].equals(wordToDelete)) {continue;}
                    records.add(new Record(parts[0], parts[1]));  // 添加记录
                }
            }
        }

        // 删除指定的记录
        String finalWordToDelete = wordToDelete;
        records.removeIf(record -> record.word.equalsIgnoreCase(finalWordToDelete));  // 使用忽略大小写的比较

        // 将更新后的记录写回文件

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(src))) {
//            writer.write("word   translation");?
//            writer.newLine();
            for (Record record : records) {
                writer.write(record.toString());  // 使用 Record 的 toString 方法
                writer.newLine();
            }
        }
    }
}
